#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

const std::string HttpSep = "\r\n";
// 可以配置的
const std::string homepage = "index.html"; // 首页
const std::string wwwroot = "./wwwroot";

class HttpRequest
{
public:
    HttpRequest() : _req_blank(HttpSep), _path(wwwroot)
    {
    }

    bool GetLine(std::string &str, std::string *line)
    {
        auto pos = str.find(HttpSep);
        if (pos == std::string::npos)
            return false;
        *line = str.substr(0, pos); // \r\n
        str.erase(0, pos + HttpSep.size());
        return true;
    }

    void Deserialize(std::string &request)
    {
        std::string line;
        bool ok = GetLine(request, &line);
        if (!ok)
            return;
        _req_line = line;

        while (true)
        {
            bool ok = GetLine(request, &line);
            if (ok && line.empty())
            {
                _req_content = request;
                break;
            }
            else if (ok && !line.empty())
            {
                _req_header.push_back(line);
            }
            else
            {
                break;
            }
        }
    }

    void ParseReqLine()
    {
        // 以空格为分隔符，提取请求行的三部分
        std::stringstream ss(_req_line);
        ss >> _method >> _url >> _http_version;

        if (_url == "/")
        {
            _path += _url;
            _path += homepage;
        }
        else
        {
            _path += _url;
        }
    }

    void ParseSuffix()
    {
        auto pos = _path.rfind(".");
        if (pos == std::string::npos)
            _suffix = ".html";
        else
            _suffix = _path.substr(pos);
    }
    void Parse()
    {
        // 1.分析请求
        ParseReqLine();
        // 2.wwwroot/dira/dirb/x.html,提取后缀
        ParseSuffix();
    }

    void DebugHttp()
    {
        std::cout << "_req_line: " << _req_line << std::endl;
        for (auto &line : _req_header)
        {
            std::cout << "---> " << line << std::endl;
        }
        std::cout << "_req_blank: " << _req_blank << std::endl;
        std::cout << "_req_content: " << _req_content << std::endl;

        std::cout << "Method: " << _method << std::endl;
        std::cout << "url: " << _url << std::endl;
        std::cout << "http_version: " << _http_version << std::endl;
    }

    std::string GetFileContentHelper(const std::string &path)
    {
        // //文本文件
        // std::ifstream in(path, std::ios::binary);
        // if(!in.is_open()) return "";
        // std::string content;
        // std::string line;
        // while(std::getline(in, line))
        // {
        //     content += line;
        // }
        // in.close();
        // return content;

        // 按二进制读取资源
        std::ifstream in(path, std::ios::binary);
        if (!in.is_open())
            return "";
        in.seekg(0, in.end);
        int filesize = in.tellg();
        in.seekg(0, in.beg);

        std::string content;
        content.resize(filesize);
        in.read((char *)content.c_str(), filesize);
        in.close();
        return content;
    }

    std::string GetFileContent()
    {
        return GetFileContentHelper(_path);
    }

    std::string Get_404()
    {
        return GetFileContentHelper("./wwwroot/404.html");
    }


    std::string Url()
    {
        return _url;
    }

    std::string Path()
    {
        return _path;
    }

    std::string Suffix()
    {
        return _suffix;
    }

    ~HttpRequest()
    {
    }

private:
    // http报文自动
    std::string _req_line; // method, url, http_version
    std::vector<std::string> _req_header;
    std::string _req_blank;
    std::string _req_content;

    // 解析之后的内容
    std::string _method;
    std::string _url;
    std::string _http_version;
    std::string _path;   //"./wwwroot"
    std::string _suffix; // 请求资源的后缀
};

const std::string BlankSep = " ";
const std::string LineSep = "\r\n";

class HttpResponse
{
public:
    HttpResponse() : _http_version("HTTP/1.0"), _status_code(200), _status_code_desc("OK"), _resp_blank(LineSep)
    {
    }

    void SetCode(int code)
    {
        _status_code = code;
    }
    
    void SetDesc(const std::string &desc)//状态码转换成状态码描述
    {
        _status_code_desc = desc;
    }
    void MakeStatusLine()
    {
        _status_line = _http_version + BlankSep + std::to_string(_status_code) + BlankSep + _status_code_desc + LineSep;
    }
    void AddHeader(const std::string &header)
    {
        _resp_header.push_back(header);
    }

    void AddContent(const std::string &content)
    {
        _resp_content = content;
    }

    std::string Serialize()
    {
        std::string response_str = _status_line;
        for (auto &header : _resp_header)
        {
            response_str += header;
        }
        response_str += _resp_blank;
        response_str += _resp_content;

        return response_str;
    }
    ~HttpResponse() {}
private:
    std::string _status_line;
    std::vector<std::string> _resp_header;
    std::string _resp_blank;
    std::string _resp_content; // body

    // httpversion StatusCode StatusCodeDesc
    std::string _http_version;
    int _status_code;
    std::string _status_code_desc;
};